package jinyilw.swing.visuals.Jcomp;

import jinyilw.common.Operator;
import jinyilw.swing.Activable;

import javax.swing.JComponent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

public class JMouseActComp extends JComponent implements Activable
{
	private static final long serialVersionUID = 7266001645194215986L;
	protected boolean isRollover, isPressed;
	protected MouseActListener mouseActListener;
	private boolean mouseActEnable, rolloverEnable, pressedEnable;
	private volatile ArrayList<Operator<Object>> operators;

	public void enableMouseAct()
	{
		rolloverEnable = true;
		pressedEnable = true;
		setActEnable(true);
	}

	public void disableMouseAct()
	{
		rolloverEnable = false;
		pressedEnable = false;
		setActEnable(false);
	}

	public void setRolloverEnable(boolean b)
	{
		rolloverEnable = b;
		if (b)
			setActEnable(true);
	}

	public void setPressedEnable(boolean b)
	{
		pressedEnable = b;
		if (b)
			setActEnable(true);
	}

	private synchronized void createClickOperators()
	{
		if (operators == null)
			operators = new ArrayList<>();
	}

	public void addClickOperator(Operator<Object> operator)
	{
		if (!mouseActEnable)
			setActEnable(true);
		if (operators == null)
			createClickOperators();
		operators.add(operator);
	}

	void setActEnable(boolean b)
	{
		if (mouseActEnable == b)
			return;
		mouseActEnable = b;
		if (b)
		{
			if (mouseActListener == null)
				mouseActListener = createMouseActListener();
			addMouseListener(mouseActListener);
		} else
			removeMouseListener(mouseActListener);
	}

	protected MouseActListener createMouseActListener()
	{
		return new MouseActListener();
	}

	@Override
	public boolean isActivated()
	{
		return isRollover;
	}

	protected class MouseActListener implements MouseListener
	{
		@Override
		public void mouseClicked(MouseEvent e)
		{
			if (operators != null && isEnabled() && e.getClickCount() == 1)
			{
				for (Operator<Object> operator : operators)
					operator.operate(e);
			}
			isRollover = false;
		}

		@Override
		public void mousePressed(MouseEvent e)
		{
			if (pressedEnable && isEnabled())
			{
				isPressed = true;
				repaint();
			}
		}

		@Override
		public void mouseReleased(MouseEvent e)
		{
			if (pressedEnable && isEnabled())
			{
				isPressed = false;
				repaint();
			}
		}

		@Override
		public void mouseEntered(MouseEvent e)
		{
			if (rolloverEnable && isEnabled())
			{
				isRollover = true;
				repaint();
			}
		}

		@Override
		public void mouseExited(MouseEvent e)
		{
			if (rolloverEnable && isEnabled())
			{
				isRollover = false;
				repaint();
			}
		}
	}
}
